﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using LitJson;

namespace eFrameWork.Manage
{
    public partial class ModelItems_Data : System.Web.UI.Page
    {
        private DataTable _alltables;//所有表
        public DataTable AllTables3
        {
            get
            {
                if (_alltables == null)
                {
                    string sql = "SELECT id,name FROM sysobjects where (xtype='U' or xtype='V') "; //name!='dtproperties' and 
                    sql += " and (charindex('a_eke_sys',lower(name))=0 or lower(name)='a_eke_sysusers' or lower(name)='a_eke_sysroles' or lower(name)='a_eke_sysmodels')";
                    sql += " and (name not in (" + eBase.getSystemTables() + ") or  lower(name)='a_eke_sysmodels' or lower(name)='a_eke_sysroles')";

                    //sql += " and (name not in (" + eBase.getSystemTables() + ") or  lower(name)='a_eke_sysmodels' or lower(name)='a_eke_sysusers')";
                    sql += " order by name";//crdate";
                   // _alltables = DataBase.getDataTable(sql);
                    _alltables = DataBase.getSchemaTableViews();
                    //eBase.PrintDataTable(_alltables);
                    //eBase.End();

                }
                return _alltables;
            }
        }

        private eDataBase _database;
        public eDataBase DataBase
        {
            get
            {
                if (_database == null)
                {
                    if (modelrow["DataSourceID"].ToString().Length > 0)
                    {
                        _database = new eDataBase(modelrow);
                    }
                    else
                    {
                        _database = eConfig.DefaultDataBase;
                    }
                }
                return _database;
            }
        }
        public string modelid = eParameters.QueryString("modelid");
        public string getJsonText(string jsonstr,string name)
        {
            StringBuilder sb = new StringBuilder();
            if (jsonstr.Length > 0)
            {
                /*
                eJson json = new eJson(jsonstr);
                foreach (eJson m in json.GetCollection())
                {
                    sb.Append("<span style=\"display:inline-block;margin-right:6px;border:1px solid #ccc;padding:3px 12px 3px 12px;\">" + HttpUtility.HtmlDecode(m.GetValue(name)) + "</span>");
                }
                */
                JsonData json = jsonstr.ToJsonData();
                foreach (JsonData m in json)
                {
                    sb.Append("<span style=\"display:inline-block;margin-right:6px;border:1px solid #ccc;padding:3px 12px 3px 12px;\">" + HttpUtility.HtmlDecode(m.getValue(name)) + "</span>");
                }
            }
            return sb.ToString();
        }
        DataRow modelrow;

        private DataTable _modelitems;
        public DataTable ModelItems
        {
            get
            {
                if (_modelitems == null)
                {
                    _modelitems = eBase.DataBase.getDataTable("select * from a_eke_sysModelItems where delTag=0 and ModelID='" + modelid + "' order by px");
                }
                return _modelitems;
            }
        }
        private eUser user;
        private int modelpx = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser("Manage");
            user.Check();
            Response.Write("<a href=\"http://frame.eketeam.com\" style=\"float:right;\" target=\"_blank\" title=\"eFrameWork开发框架\"><img src=\"images/help.gif\"></a>");
            
            if (eConfig.showHelp())
            {
                Response.Write("<div class=\"tips\" style=\"margin-bottom:8px;\">");
                Response.Write("<b>数据</b><br>");
                Response.Write("设置列(单选框、复选框、下拉框)的选项数据来源。<br>");
                Response.Write("</div> ");
            }
            modelrow = eBase.DataBase.getDataTable("select * from a_eke_sysModels where ModelID='" + modelid + "'").Select()[0];

            /*
             * 
            eList datalist = new eList("a_eke_sysModelItems");
            datalist.Where.Add("ModelID='" + modelid + "' and delTag=0");
            //datalist.Where.Add("(Sys=0 or Code like '%User') and (showAdd=1 or showList=1) and (Code like '%User' or (Custom=1 or ControlType='searchselect' or ControlType='radio' or ControlType='checkbox' or ControlType='select' or ControlType='autoselect'))");//自定义列也要可以取值 Custom=0 and 
            datalist.Where.Add("(showAdd=1 or showList=1 or showExport=1)");
            datalist.OrderBy.Add("px");
            //Rep.ItemDataBound += new RepeaterItemEventHandler(Rep_ItemDataBound);
            //datalist.Bind(Rep);

            //Rep.ItemDataBound += new RepeaterItemEventHandler(Rep_ItemDataBound);
            Rep.ItemDataBound += Rep_ItemDataBound;
            Rep.DataSource = ModelItems.Select("", "showAdd=1 or showList=1 or showExport=1", "px,addtime");

           // Rep.DataSource = ModelItems.Select("", "showAdd=1 or showList=1 or showExport=1", "px,addtime");
            Rep.DataBind();
            */
            list();

            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            Rep.RenderControl(htw);
            Rep.Visible = false;//不输出，要在获取后设，不然取不到内容。
            Response.Write(sw.ToString());
            sw.Close();
            Response.End();
        }
        private void list()
        {
            DataTable tb = getItems(modelid);
            appendItems(tb, modelid);
            //eBase.PrintDataTable(tb.Select("mc,code", "code is null or code not in ('addtime','edittime','deltime','deltag')", ""));
           // eBase.PrintDataRow(tb.Select("Convert(code, 'System.String') not in ('addtime','edittime','deltime','deltag')", "showAdd desc,showList desc,showExport desc,PX, addTime"));
            //tb = tb.Select("showAdd=1 or showList=1 or showExport=1", "PX, addTime").toDataTable();
            //tb = tb.Select("code is null or code not in ('addtime','edittime','deltime','deltag')", "showAdd desc,showList desc,showExport desc,modelpx,PX, addTime").toDataTable();
            string pid = eParameters.QueryString("modelid");          
            for (int i = tb.Rows.Count - 1; i > -1; i--)
            {
                if (tb.Rows[i]["modelid"].ToString() != pid)
                {
                    if (",addTime,addUser,editTime,editUser,delTime,delUser,delTag,CheckupCode,CheckupText,".ToLower().Contains("," + tb.Rows[i]["Code"].ToString().ToLower() + ","))
                    {
                        tb.Rows.Remove(tb.Rows[i]);
                    }
                }
            }
            tb = tb.Select("", "showAdd desc,showList desc,showExport desc,modelpx,PX, addTime").toDataTable();

            Rep.ItemDataBound += Rep_ItemDataBound;
            Rep.DataSource = tb;
            Rep.DataBind();
        }
        private DataTable getItems(string modelid)
        {
            modelpx++;
            return eBase.DataBase.getDataTable("select " + modelpx.ToString() + " as modelpx,b.mc as ModelName,a.* from a_eke_sysModelItems a inner join a_eke_sysModels b on a.modelid=b.modelid where a.ModelID='" + modelid + "' and a.delTag=0");
        }
        private void appendItems(DataTable tb, string modelid)
        {
            DataTable dt = eBase.DataBase.getDataTable("select modelid,mc from a_eke_sysModels where ParentID='" + modelid + "' and JoinMore=0 and show=1 and deltag=0");
            foreach (DataRow dr in dt.Rows)
            {
                DataTable tb2 = getItems(dr["modelid"].ToString());
                foreach (DataRow _dr in tb2.Rows)
                {
                    tb.Rows.Add(_dr.ItemArray);
                }
                appendItems(tb, dr["modelid"].ToString());
            }
        }
        protected void Rep_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            string sql = "";
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
               
                Control ctrl = e.Item.Controls[0];
                #region 数据绑定
                Literal lit = (Literal)ctrl.FindControl("LitObjects");
                if (lit != null)
                {
                    eDataBase db;
                    string dsid = DataBinder.Eval(e.Item.DataItem, "DataSourceID").ToString();

                    if (dsid.Length == 0)
                    {
                        db = DataBase;
                    }
                    else if (dsid == "maindb")
                    {
                        db = eConfig.DefaultDataBase;
                    }
                    else
                    {
                        db = new eDataBase(new Guid(dsid));
                    }

                    DataTable AllTables = db.getSchemaTableViews();
                    //eBase.PrintDataTable(AllTables);
                    //eBase.Writeln(db.ConnectionString);

                    //eBase.Writeln(DataBinder.Eval(e.Item.DataItem, "DataSourceID").ToString());

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < AllTables.Rows.Count; i++)
                    {
                        sb.Append("<option value=\"" + AllTables.Rows[i]["value"].ToString() + "\"" + (DataBinder.Eval(e.Item.DataItem, "BindObject").ToString().ToLower() == AllTables.Rows[i]["value"].ToString().ToLower() ? " selected=\"true\"" : "") + " title=\"" + AllTables.Rows[i]["text"].ToString() + "\">" + AllTables.Rows[i]["text"].ToString() + "</option>\r\n");
                    }
                    lit.Text = sb.ToString();

                    if (DataBinder.Eval(e.Item.DataItem, "BindObject").ToString().Length > 0)
                    {
                        lit = (Literal)ctrl.FindControl("LitValue");
                        if (lit != null)
                        {
                            //绑定表-列
                            DataTable cols = db.getSchemaColumns(DataBinder.Eval(e.Item.DataItem, "BindObject").ToString());
                           // eBase.PrintDataTable(cols);
                            if (cols.Rows.Count == 0) return;

                            //sql = "select b.name from sysobjects a inner join  syscolumns b on a.id=b.id where a.name='" + DataBinder.Eval(e.Item.DataItem, "BindObject").ToString() + "' order by b.colid";//b.colid";
                            //lit.Text = DataBase.getOptions(sql, "name", "name", DataBinder.Eval(e.Item.DataItem, "BindValue").ToString());
                            lit.Text = cols.toOptions("COLUMN_NAME", "COLUMN_NAME", DataBinder.Eval(e.Item.DataItem, "BindValue").ToString());

                            lit = (Literal)ctrl.FindControl("LitText");
                            if (lit != null)
                            {
                                //lit.Text = DataBase.getOptions(sql, "name", "name", DataBinder.Eval(e.Item.DataItem, "BindText").ToString());
                                lit.Text = cols.toOptions("COLUMN_NAME", "COLUMN_NAME", DataBinder.Eval(e.Item.DataItem, "BindText").ToString());
                            }
                            lit = (Literal)ctrl.FindControl("LitCode");
                            if (lit != null)
                            {
                                //lit.Text = DataBase.getOptions(sql, "name", "name", DataBinder.Eval(e.Item.DataItem, "BindText").ToString());
                                lit.Text = cols.toOptions("COLUMN_NAME", "COLUMN_NAME", DataBinder.Eval(e.Item.DataItem, "BindCode").ToString());
                            }


                            #region 外键
                            lit = (Literal)ctrl.FindControl("LitBindForeignKey");
                            if (lit != null)
                            {
                                string bindfk = DataBinder.Eval(e.Item.DataItem, "BindForeignKey").ToString();
                                //if (bindfk.Length == 0) bindfk = "ParentID";
                                sql = "select b.name from sysobjects a inner join  syscolumns b on a.id=b.id ";
                                sql += " inner join systypes c on b.xtype=c.xusertype ";
                                sql+=" where a.name='" + DataBinder.Eval(e.Item.DataItem, "BindObject").ToString() + "'";
                                sql += " and b.name not in ('addtime','adduser','edittime','edituser','deltime','deluser','deltag','" + DataBinder.Eval(e.Item.DataItem, "BindValue").ToString() + "')";
                                sql += " and (charindex('int',c.name)>0 or charindex('varchar',c.name)>0 or charindex('uniqueidentifier',c.name)>0) ";
                                sql +=" order by b.colid";
                                //lit.Text = DataBase.getOptions(sql, "name", "name", bindfk);
                                //eBase.PrintDataTable(DataBase.getDataTable(sql));
                                //eBase.PrintDataTable(cols);
                                lit.Text += cols.Select("", "DATA_TYPE in ('int','uniqueidentifier','char','nchar','varchar','nvarchar') and COLUMN_NAME not in ('addtime','adduser','edittime','edituser','deltime','deluser','deltag','" + DataBinder.Eval(e.Item.DataItem, "BindValue").ToString() + "')", "ORDINAL_POSITION").toOptions("COLUMN_NAME", "COLUMN_NAME", bindfk);
                            }
                            #endregion
                        }
                    }
                }
                #endregion
                #region 联动加载
                lit = (Literal)ctrl.FindControl("Litcolumns");
                if (lit != null)
                {
                    sql = "SELECT ModelItemID,MC FROM a_eke_sysModelItems ";
                    sql += " where ModelID='" + DataBinder.Eval(e.Item.DataItem, "ModelID").ToString() + "' and len(BindObject)>0 ";
                    sql += " and ModelItemID<>'" + DataBinder.Eval(e.Item.DataItem, "ModelItemID").ToString() + "' ";
                    sql += " and ControlType in ('select','radio','checkbox','autoselect') ";
                    //lit.Text = eBase.DataBase.getOptions(sql, "mc", "ModelItemID", DataBinder.Eval(e.Item.DataItem, "FillItem").ToString());
                    //lit.Text = ModelItems.Select("", "len(Convert(BindObject, 'System.String'))>0  and BindAuto=0 and Convert(ModelItemID, 'System.String')<>'" + DataBinder.Eval(e.Item.DataItem, "ModelItemID").ToString() + "' and ControlType in ('select','radio','checkbox')", "").toOptions("ModelItemID", "MC", DataBinder.Eval(e.Item.DataItem, "FillItem").ToString());
                    DataTable tb = ModelItems.Select("", "(len(Convert(BindObject, 'System.String'))>0 or len(bindsql)>0) and showAdd=1 and BindAuto=0 and Convert(ModelItemID, 'System.String')<>'" + DataBinder.Eval(e.Item.DataItem, "ModelItemID").ToString() + "' and ControlType in ('select','radio','checkbox','autoselect')", "");
                    
                    StringBuilder sb = new StringBuilder();
                    string curitemid = DataBinder.Eval(e.Item.DataItem, "ModelItemID").ToString();
                    foreach (DataRow dr in tb.Rows)
                    {
                        DataRow[] myrows = ModelItems.Select("ModelItemID='" + curitemid + "' and FillItem like '%" + dr["ModelItemID"].ToString() + "%'");
                        DataRow[] allrows = ModelItems.Select("FillItem like '%" + dr["ModelItemID"].ToString() + "%'");
                        if (myrows.Length > 0 || allrows.Length == 0)
                        {
                            sb.Append("<label><input reload=\"true\" type=\"checkbox\" name=\"fillitem_" + curitemid.Replace("-", "") + "\"");
                            sb.Append(" onclick=\"setModelItem_FillItem(this,'fillitem_" + curitemid.Replace("-", "") + "','" + curitemid + "','fillitem');\" value=\"" + dr["ModelItemID"].ToString() + "\"");
                            if (DataBinder.Eval(e.Item.DataItem, "FillItem").ToString().ToLower().IndexOf(dr["ModelItemID"].ToString()) > -1) sb.Append(" checked");
                            sb.Append(" />");
                            sb.Append(dr["MC"].ToString()  + "</label>");
                        }
                    }
                    lit.Text = sb.ToString().Length > 10 ? sb.ToString() : "无";
                }
                #endregion
            }
        }
    }
}